package com.teaching.management.controller.api;

import com.teaching.management.entity.Classroom;
import com.teaching.management.entity.User;
import com.teaching.management.repository.ClassroomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;

/**
 * 教室管理相关的REST API
 */
@RestController
@RequestMapping("/api/admin/classrooms")
public class AdminClassroomRestController {

    @Autowired
    private ClassroomRepository classroomRepository;

    /**
     * 获取所有教室
     */
    @GetMapping
    public ResponseEntity<?> getAllClassrooms(HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        List<Classroom> classrooms = classroomRepository.findAll();
        return ResponseEntity.ok(classrooms);
    }

    /**
     * 根据条件搜索教室
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchClassrooms(@RequestParam("term") String searchTerm, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 创建模糊匹配，匹配教室编号或教学楼
        Classroom example = new Classroom();
        example.setClassroomId(searchTerm);
        example.setBuilding(searchTerm);

        ExampleMatcher matcher = ExampleMatcher.matchingAny()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();

        List<Classroom> classrooms = classroomRepository.findAll(Example.of(example, matcher));
        return ResponseEntity.ok(classrooms);
    }

    /**
     * 获取单个教室详情
     */
    @GetMapping("/{classroomId}")
    public ResponseEntity<?> getClassroom(@PathVariable String classroomId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        Optional<Classroom> classroomOpt = classroomRepository.findById(classroomId);
        if (classroomOpt.isPresent()) {
            return ResponseEntity.ok(classroomOpt.get());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("教室不存在");
        }
    }

    /**
     * 添加新教室
     */
    @PostMapping
    public ResponseEntity<?> addClassroom(@RequestBody Classroom classroom, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查教室ID是否已存在
        if (classroomRepository.existsById(classroom.getClassroomId())) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("教室编号已存在");
        }

        Classroom savedClassroom = classroomRepository.save(classroom);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedClassroom);
    }

    /**
     * 更新教室信息
     */
    @PutMapping("/{classroomId}")
    public ResponseEntity<?> updateClassroom(
            @PathVariable String classroomId,
            @RequestBody Classroom classroom,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 确保路径中的ID与请求体中的ID一致
        if (!classroomId.equals(classroom.getClassroomId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("教室编号不一致");
        }

        // 检查教室是否存在
        if (!classroomRepository.existsById(classroomId)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("教室不存在");
        }

        Classroom updatedClassroom = classroomRepository.save(classroom);
        return ResponseEntity.ok(updatedClassroom);
    }

    /**
     * 删除教室
     */
    @DeleteMapping("/{classroomId}")
    public ResponseEntity<?> deleteClassroom(@PathVariable String classroomId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查教室是否存在
        if (!classroomRepository.existsById(classroomId)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("教室不存在");
        }

        try {
            classroomRepository.deleteById(classroomId);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 可能因为外键约束而无法删除
            return ResponseEntity.status(HttpStatus.CONFLICT)
                    .body("删除失败，该教室已被课程引用，请先解除关联");
        }
    }
}